package com.ruoyi.safe.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import cn.hutool.core.util.IdUtil;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.quality.domain.TQualityFileItem;
import com.ruoyi.quality.mapper.TQualityFileItemMapper;
import com.ruoyi.quality.service.impl.TQualityFileItemServiceImpl;
import com.ruoyi.safe.domain.BizProjectCheckRecord;
import com.ruoyi.safe.domain.BizSafeAttach;
import com.ruoyi.safe.domain.BizSecurityRecord;
import com.ruoyi.safe.domain.dto.BizLogStatisticsDTO;
import com.ruoyi.safe.domain.dto.BizRecordIdsDTO;
import com.ruoyi.safe.mapper.BizProjectCheckRecordMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.safe.mapper.BizSecurityLogMapper;
import com.ruoyi.safe.domain.BizSecurityLog;
import com.ruoyi.safe.service.IBizSecurityLogService;
import org.springframework.util.CollectionUtils;

/**
 * 安全日志Service业务层处理
 *
 * @author ruoyi
 * @date 2023-12-01
 */
@Service
@Slf4j
public class BizSecurityLogServiceImpl implements IBizSecurityLogService {
    @Autowired
    private BizSecurityLogMapper bizSecurityLogMapper;
    @Autowired
    private BizProjectCheckRecordMapper bizProjectCheckRecordMapper;
    @Autowired
    private BizSafeAttachServiceImpl bizSafeAttachService;
    @Autowired
    private TQualityFileItemMapper tQualityFileItemMapper;

    /**
     * 查询安全日志
     *
     * @param id 安全日志主键
     * @return 安全日志
     */
    @Override
    public BizSecurityLog selectBizSecurityLogById(Long id) {
        BizSecurityLog bizSecurityLog = bizSecurityLogMapper.selectBizSecurityLogById(id);
        if (bizSecurityLog == null) {
            return new BizSecurityLog();
        }
        bizSecurityLog.setTime(bizSecurityLog.getSecurityDate());
        List<Long> recordIds = bizSecurityLogMapper.selectRecordList(id);
        bizSecurityLog.setRecordIds(recordIds);

        List<BizSafeAttach> bizSafeAttaches = bizSafeAttachService.selectBizSafeAttachByBizIds(new Long[]{id});
        bizSecurityLog.setAttachList(bizSafeAttaches);

        return bizSecurityLog;
    }

    /**
     * 查询安全日志列表
     *
     * @param bizSecurityLog 安全日志
     * @return 安全日志
     */
    @Override
    public List<BizSecurityLog> selectBizSecurityLogList(BizSecurityLog bizSecurityLog) {
        List<BizSecurityLog> bizSecurityLogList = bizSecurityLogMapper.selectBizSecurityLogList(bizSecurityLog);
        setRecordIdsAndPhoto(bizSecurityLogList);
        return bizSecurityLogList;
    }

    /**
     * 日志视图--本月数据
     *
     * @param bizSecurityLog
     * @return
     */
    @Override
    public List<BizSecurityLog> selectLogList(BizSecurityLog bizSecurityLog, SysUser sysUser) {
        if ("2".equals(bizSecurityLog.getSecurityType()) && bizSecurityLog.getSercurityPeople() == null) {
            bizSecurityLog.setSercurityPeople(sysUser.getUserName());
        }
        List<BizSecurityLog> logs = bizSecurityLogMapper.selectLogList(bizSecurityLog);
        return logs;
    }

    /**
     * 新增安全日志
     *
     * @param bizSecurityLog 安全日志
     * @param sysUser 用户信息
     * @return 结果
     */
    @Override
    public int insertBizSecurityLog(BizSecurityLog bizSecurityLog, SysUser sysUser) {

        bizSecurityLog.setCreateBy(sysUser.getUserName());
        //一天只能新增一条
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        // List<BizSecurityLog> count = bizSecurityLogMapper.selectListByCreateTime(sdf.format(DateUtils.getNowDate()));
        int logIdCount = 0;
        if ("1".equals(bizSecurityLog.getSecurityType())) {
            // 类型是项目日志
            logIdCount = bizSecurityLogMapper
                    .selectLogIdByTime(sdf.format(bizSecurityLog.getTime()), bizSecurityLog.getProjectId(), bizSecurityLog.getSecurityType(), null);//根据传来的time来查看有几个logId
        } else if ("2".equals(bizSecurityLog.getSecurityType())) {
            // 类型是个人日志
            logIdCount = bizSecurityLogMapper
                    .selectLogIdByTime(sdf.format(bizSecurityLog.getTime()), bizSecurityLog.getProjectId(), bizSecurityLog.getSecurityType(), bizSecurityLog.getCreateBy());//根据传来的time来查看有几个logId
        } else {
            throw new RuntimeException("日志类型问题");
        }

        //如果当前日期和前端传来的之前日期有数据
        if (logIdCount > 0) {
            throw new RuntimeException("选择的日期已新增过日志");
        }
        //如果今天没有新增日志并且前端传递来的时间等于当前时间
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
        bizSecurityLog.setCreateTime(DateUtils.getNowDate());
        bizSecurityLog.setId(IdUtil.getSnowflakeNextId());
        bizSecurityLog.setEvent(sysUser.getNickName() + "创建于" + simpleDateFormat.format(DateUtils.getNowDate()));

        //如果是新增个人日志，创建者只能新增安全员是自己的
//        String checkPeople = bizProjectCheckRecordMapper.selectListByUserId(sysUser.getUserId());
        if (("2").equals(bizSecurityLog.getSecurityType())) {
//            if (!sysUser.getUserName().equals(checkPeople)) {
//                throw new RuntimeException("新增个人日志只能创建自己的");
//            }
            bizSecurityLog.setSercurityPeople(sysUser.getUserName());
        }
        //新增到安全日志-检查记录表中
        if (!CollectionUtils.isEmpty(bizSecurityLog.getRecordIds())) {
            bizSecurityLog.setCheckRecordCount(Long.valueOf(bizSecurityLog.getRecordIds().size()));
            //新增到日志检查记录表中
            List<BizSecurityRecord> collect = bizSecurityLog.getRecordIds().stream().map(recordId -> {
                BizSecurityRecord bizSecurityRecord = new BizSecurityRecord();
                bizSecurityRecord.setLogId(bizSecurityLog.getId());
                bizSecurityRecord.setRecordId(recordId);
                return bizSecurityRecord;
            }).collect(Collectors.toList());
            bizSecurityLogMapper.insertIntoSecurityRecord(collect);
        }
        bizSecurityLog.setSecurityDate(bizSecurityLog.getTime());
        if (bizSecurityLog.getSecnePhoto() != null) {
            String fileName = getFileName(bizSecurityLog.getSecnePhoto());
            bizSafeAttachService.selectBizSafeAttachByNames(fileName, bizSecurityLog.getId());
        }
        return bizSecurityLogMapper.insertBizSecurityLog(bizSecurityLog);

    }

    /**
     *  去掉secnePhoto中的http:ip等字符，只保留文件名和扩展名，重新拼接成以","分割的字符串返回
     *  eg:
     *  输入：secnePhoto = "http://x.x.x.x:x/lqsafe/112233_1_20240206134734A001.png,http://x.x.x.x:x/lqsafe/112233_1_20240206134737A002.png"
     *  输出："112233_1_20240206134734A001.png,112233_1_20240206134737A002.png"
     * @param secnePhoto secnePhoto
     * @return
     */
    private String getFileName(String secnePhoto) {
        if(secnePhoto != null){
            String[] photo = secnePhoto.split(",");
            StringBuilder sb = new StringBuilder();
            Arrays.stream(photo).forEach(str -> sb.append(str.substring(str.lastIndexOf('/') + 1)).append(','));
            return sb.substring(0, sb.length() - 1);
        }else{
            return "";
        }

    }

    /**
     * 修改安全日志
     *
     * @param bizSecurityLog 安全日志
     * @param sysUser 用户信息
     * @return 结果
     */
    @Override
    public int updateBizSecurityLog(BizSecurityLog bizSecurityLog, SysUser sysUser) {
        bizSecurityLog.setUpdateBy(sysUser.getUserName());
        bizSecurityLog.setUpdateTime(DateUtils.getNowDate());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
        bizSecurityLog.setEvent(sysUser.getNickName() + "创建于" + simpleDateFormat.format(DateUtils.getNowDate()));

        List<Long> dbRecordIds = bizSecurityLogMapper.selectRecordList(bizSecurityLog.getId());
        List<Long> inputRecordIds = bizSecurityLog.getRecordIds();

        List<Long> needDelRecordIds = new ArrayList<>();
        List<Long> needAddRecordIds = new ArrayList<>();
        for (Long id : dbRecordIds) {
            if (!inputRecordIds.contains(id)) {
                needDelRecordIds.add(id);
            }
        }

        for (Long id : inputRecordIds) {
            if (!dbRecordIds.contains(id)) {
                needAddRecordIds.add(id);
            }
        }

        if (!CollectionUtils.isEmpty(needAddRecordIds)) {
            // 此时needAddRecordIds的数据时需要新增的
            List<BizSecurityRecord> collect = needAddRecordIds.stream().map(recordId -> {
                BizSecurityRecord bizSecurityRecord = new BizSecurityRecord();
                bizSecurityRecord.setLogId(bizSecurityLog.getId());
                bizSecurityRecord.setRecordId(recordId);
                return bizSecurityRecord;
            }).collect(Collectors.toList());
            bizSecurityLogMapper.insertIntoSecurityRecord(collect);
        }

        if (!CollectionUtils.isEmpty(needDelRecordIds)) {
            // 此时needDelRecordIds的数据时需要删掉的
            needDelRecordIds.forEach(recordId -> {
                BizSecurityRecord bizSecurityRecord = new BizSecurityRecord();
                bizSecurityRecord.setLogId(bizSecurityLog.getId());
                bizSecurityRecord.setRecordId(recordId);
                bizSecurityLogMapper.deleteSecurityRecord(bizSecurityRecord);
            });
        }
        bizSecurityLog.setCheckRecordCount(Long.valueOf(inputRecordIds.size()));
        String fileName = getFileName(bizSecurityLog.getSecnePhoto());
        bizSafeAttachService.updateBizSafeAttachByBizId(fileName, bizSecurityLog.getId());

        return bizSecurityLogMapper.updateBizSecurityLog(bizSecurityLog);
    }

    /**
     * 批量删除安全日志
     *
     * @param ids 需要删除的安全日志主键
     * @return 结果
     */
    @Override
    public int deleteBizSecurityLogByIds(Long[] ids) {
        return bizSecurityLogMapper.deleteBizSecurityLogByIds(ids);
    }

    /**
     * 删除安全日志信息
     *
     * @param id 安全日志主键
     * @return 结果
     */
    @Override
    public int deleteBizSecurityLogById(Long id) {
        return bizSecurityLogMapper.deleteBizSecurityLogById(id);
    }

    @Override
    public List<Map<String, Object>> selectLogStatistics(BizLogStatisticsDTO bizLogStatisticsDTO) {
        //查询条件
        if(StringUtils.isNotNull(bizLogStatisticsDTO.getSecurityDate())){
            bizLogStatisticsDTO.setStartTime(bizLogStatisticsDTO.getSecurityDate()[0]);
            bizLogStatisticsDTO.setEndTime(bizLogStatisticsDTO.getSecurityDate()[1]);
        }
        return bizSecurityLogMapper.selectLogStatistics(bizLogStatisticsDTO);
    }

    @Override
    public List<BizSecurityLog> selectListByProjectId(Long projectId) {
        return bizSecurityLogMapper.selectListByProjectId(projectId);
    }

    @Override
    public int insertRecords(BizRecordIdsDTO bizRecordIdsDTO) {
        List<BizSecurityRecord> list = new ArrayList<>();
        for (Long recordId : bizRecordIdsDTO.getRecordIds()) {
            BizSecurityRecord bizSecurityRecord = new BizSecurityRecord();
//            bizSecurityRecord.setLogId(id);
            bizSecurityRecord.setRecordId(recordId);
            bizSecurityRecord.setCreateTime(bizRecordIdsDTO.getCreateTime());
            list.add(bizSecurityRecord);
        }
        return bizSecurityLogMapper.insertRecordIds(list);
    }

    @Override
    public List<BizSecurityLog> selectListByDto(BizLogStatisticsDTO bizLogStatisticsDTO) {
        //查询条件
        if(StringUtils.isNotNull(bizLogStatisticsDTO.getSecurityDate())){
            bizLogStatisticsDTO.setStartTime(bizLogStatisticsDTO.getSecurityDate()[0]);
            bizLogStatisticsDTO.setEndTime(bizLogStatisticsDTO.getSecurityDate()[1]);
        }

        List<BizSecurityLog> bizSecurityLogList = bizSecurityLogMapper.selectListByDto(bizLogStatisticsDTO);
        setRecordIdsAndPhoto(bizSecurityLogList);
        return bizSecurityLogList;
    }

    private void setRecordIdsAndPhoto(List<BizSecurityLog> bizSecurityLogList) {
        bizSecurityLogList.forEach(item -> {
            item.setTime(item.getSecurityDate());
            List<Long> recordIds = bizSecurityLogMapper.selectRecordList(item.getId());
            item.setRecordIds(recordIds);

            if (!CollectionUtils.isEmpty(recordIds)) {
                List<TQualityFileItem> records = tQualityFileItemMapper
                        .selectTQualityFileItemByIds(recordIds.toArray(new Long[0]));
//                item.setHiddenDangerNum(records.stream().filter(r -> Stream.of("1", "2", "3")
//                        .collect(Collectors.toSet()).contains(r.getHiddenDangerStatus())).count());
            }

            List<BizSafeAttach> bizSafeAttaches = bizSafeAttachService.selectBizSafeAttachByBizIds(new Long[]{item.getId()});
            item.setAttachList(bizSafeAttaches);
        });
    }

}
